package com.hsgene.order.controller.console;

import com.hsgene.common.ClientType;
import com.hsgene.common.exception.CommonErrorCode;
import com.hsgene.common.util.basic.SimpleRegexUtils;
import com.hsgene.common.util.basic.SimpleStringUtils;
import com.hsgene.common.util.exception.ErrorCode;
import com.hsgene.common.util.resolver.FromSession;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.result.NullObject;
import com.hsgene.common.util.support.LimitHelper;
import com.hsgene.common.util.support.Pagination;
import com.hsgene.common.util.support.PeanutPagination;
import com.hsgene.common.util.web.session.UserInfo;
import com.hsgene.order.condition.DistributeOrderCondition;
import com.hsgene.order.condition.QueryTestingProductOrderCondition;
import com.hsgene.order.condition.SettlementCondition;
import com.hsgene.order.controller.peanut.OrderController;
import com.hsgene.order.domain.OrderPackage;
import com.hsgene.order.domain.OrderPackageDetail;
import com.hsgene.order.domain.PlatformOrderDto;
import com.hsgene.order.domain.v1.*;
import com.hsgene.order.dto.console.*;
import com.hsgene.order.dto.peanut.OrderCheckInfoDto;
import com.hsgene.order.dto.v1.GeneticTestingExpressDeliveryDto;
import com.hsgene.order.exception.OrderErrorCode;
import com.hsgene.order.service.ConsoleOrderService;
import com.hsgene.order.service.OrderRefundService;
import com.hsgene.order.service.OrderService;
import com.hsgene.user.domain.DoctorDto;
import com.hsgene.user.dto.address.AddressDetails;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @desc: 运营后台订单管理
 * @author: 江承良
 * @date: 2018/9/25 14:53
 */
@RestController
@RequestMapping("/v1.0/genetic/testing")
public class ConsoleOrderController {
    /**
     * Log
     */
    private Logger logger = LogManager.getLogger(ConsoleOrderController.class);

    @Autowired
    private ConsoleOrderService consoleOrderService;

    @Resource
    private OrderRefundService orderRefundService;

    @Resource
    private OrderService orderService;

    /**
     * 线下付款弹窗信息
     *
     * @param id 订单id
     * @return
     */
    @GetMapping("order/underline/payment/{order_id}")
    public ApiResult underLinePaymentInfo(@PathVariable("order_id") String id) {
        try {
            ApiResult apiResult = consoleOrderService.underLinePaymentInfo(id);
            return apiResult;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("query under line payment info error", e);
            return new ApiResult(50015, "failed", "获取弹窗信息失败", null);
        }
    }

    /**
     * 保存线下付款信息并更新订单状态
     *
     * @return
     */
    @PutMapping("order/underline/payment/{order_id}")
    public ApiResult updateUnderLinePayment(@RequestBody GeneticTestingOrderAddtionB geneticTestingOrderAddtionB,
                                            @PathVariable("order_id") String id, @FromSession UserInfo userInfo) {
        try {
            if (userInfo == null) {
                return new ApiResult(5001, "failed", "用户信息获取失败，请尝试刷新或重新登录", null);
            }
            ApiResult result = consoleOrderService.updateTestingOrder(geneticTestingOrderAddtionB, userInfo.getUserId
                    ());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("update under line payment info error", e);
            return new ApiResult(50016, "failed", "保存失败", null);
        }
    }

    /**
     * 订单分配列表
     *
     * @param condition
     * @param page
     * @param size
     * @return
     */
    @GetMapping("orders/distribute")
    public ApiResult distributeOrders(DistributeOrderCondition condition, Integer page, Integer size) {
        try {
            if (page == null || size == null) {
                return new ApiResult(50017, "failed", "分页条件不能为空", null);
            }
            LimitHelper limitHelper = LimitHelper.create(page, size, true);
            condition.setLimitHelper(limitHelper);
            return consoleOrderService.distributeOrders(condition);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("orders distribute page error", e);
            return new ApiResult(500, "failed", "获取数据出错", e.toString());
        }
    }

    /**
     * 待分配订单详情
     *
     * @param id
     * @return
     */
    @GetMapping("orders/distribute/{id}")
    public ApiResult distributeOrderDetail(@PathVariable("id") String id) {
        try {
            return consoleOrderService.distributeOrderDetail(id);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("orders distribute detail error", e);
            return new ApiResult(500, "failed", "获取数据出错", e.toString());
        }
    }

    /***
     * @Description 给订单分配地服
     * @Author jcl
     * @CreateDate 2018/10/18 15:36
     * @Param assigneeId 地服id
     * @Return
     */
    @PutMapping("orders/distribute")
    public ApiResult distributeDifu(@RequestBody DistributeDifuDto distributeDifuDto, @FromSession UserInfo userInfo) {
        try {
            String distributorId = null;
            if (userInfo != null) {
                distributorId = userInfo.getUserId();
            }
            return consoleOrderService.distributeDifu(distributeDifuDto.getOrderId(), distributorId,
                    distributeDifuDto.getAssigneeId());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("orders distribute error", e);
            return new ApiResult(500, "failed", "系统错误", e.toString());
        }
    }

    /**
     * 查询订单退款信息
     *
     * @param orderId 订单id
     * @return 订单退款信息
     */
    @GetMapping("orders/{order_id}/refund")
    public ApiResult<OrderRefundInfoDto> findOrderRefundInfo(
            @PathVariable("order_id") String orderId) {
        return orderRefundService.findOrderRefundInfo(orderId);
    }

    /**
     * 订单申请退款
     *
     * @param orderId     订单id
     * @param orderRefund 退款申请信息
     * @return 申请退款结果
     */
    @PutMapping("orders/{order_id}/refund")
    public ApiResult<NullObject> orderRefund(
            @PathVariable("order_id") String orderId,
            @RequestBody OrderRefundInfoDto orderRefund,
            @FromSession UserInfo userInfo) {
        orderRefund.setOrderId(orderId);
        return orderRefundService.orderRefund(orderRefund, userInfo.getUserId());
    }

    /**
     * @param orderId 订单id
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.order.dto.console.OrderUpdateDto>
     * @description 根据订单id获取订单修改信息
     * @author maodi
     * @createDate 2018/11/27 14:19
     */
    @GetMapping("platform/orders/{order_id}")
    public ApiResult<OrderUpdateDto> queryOrderUpdate(@PathVariable("order_id") String orderId) {
        try {
            if (StringUtils.isBlank(orderId)) {
                return ApiResult.fail(OrderErrorCode.ORDER_ID_IS_NOT_NULL);
            }
            return ApiResult.succ(consoleOrderService.queryOrderUpdate(orderId));
        } catch (Exception e) {
            logger.error(OrderErrorCode.QUERY_ORDER_UPDATE_BY_ORDER_ID_IS_ERROR.getMessage(), e);
            return ApiResult.fail(OrderErrorCode.QUERY_ORDER_UPDATE_BY_ORDER_ID_IS_ERROR);
        }
    }

    /**
     * @param orderId          订单id
     * @param platformOrderDto 平台订单信息
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.common.util.result.NullObject>
     * @description 修改订单信息/修改订单医生
     * @author maodi
     * @createDate 2018/11/5 14:52
     */
    @PutMapping("platform/orders/{order_id}")
    public ApiResult<NullObject> updatePlatformOrder(@PathVariable("order_id") String orderId,
                                                     @RequestBody PlatformOrderDto platformOrderDto,
                                                     @FromSession UserInfo userInfo) {
        if (StringUtils.isBlank(orderId)) {
            return ApiResult.fail(OrderErrorCode.ORDER_ID_IS_NOT_NULL);
        }
        platformOrderDto.setOrderId(orderId);
        Integer type = platformOrderDto.getType();
        if (type == null) {
            return ApiResult.fail(CommonErrorCode.RANGE_TYPE_IS_NULL);
        }
        if (type != 1 && type != 2) {
            return ApiResult.fail(OrderErrorCode.UPDATE_PLATFORM_ORDER_TYPE_IS_ERROR);
        }
        ErrorCode code = checkPlatformOrder(platformOrderDto, type);
        if (code != null) {
            return ApiResult.fail(code);
        }
        if (1 == type) {
            platformOrderDto.setDoctorId(null);
            code = OrderErrorCode.UPDATE_PLATFORM_ORDER_IS_ERROR;
        } else {
            int isChangedDoctor = consoleOrderService.queryIsChangedDoctor(orderId);
            if (isChangedDoctor != 0) {
                return ApiResult.fail(OrderErrorCode.ORDER_DOCTOR_HAVE_BEEN_UPDATED);
            }
            platformOrderDto.setName(null);
            platformOrderDto.setAge(null);
            platformOrderDto.setSex(null);
            platformOrderDto.setPhone(null);
            platformOrderDto.setClinicalDiagnosis(null);
            code = OrderErrorCode.UPDATE_PLATFORM_ORDER_DOCTOR_IS_ERROR;
            //判断是否完成了第二次补全（快递公司，快递时间，快递备注，快递单号、快递回单、样本图片等信息）
            //快递回单、样本图片是否为空
            OrderCheckInfoDto result = orderService.checkOrderSample(orderId);
            if (result == null || StringUtils.isEmpty(result.getExpressImages()) || StringUtils.isEmpty(result.getSampleImages()) || result.getGoodsConsumes() == null ) {
                logger.error("goods consumes order info is not complete", new IllegalArgumentException());
                return ApiResult.failFormatTip(OrderErrorCode.ORDER_IS_NOT_COMPLETED, "耗材信息");
            }
            //验证快递公司，快递时间，快递备注，快递单号是否为空
            OrderCheckInfoDto checkInfoDto = orderService.checkPackageDeliver(orderId);
            List<GeneticTestingExpressDeliveryDto> deliveryDtos = checkInfoDto.getDeliveryDtos();
            if(deliveryDtos==null){
                return ApiResult.failFormatTip(OrderErrorCode.ORDER_IS_NOT_COMPLETED, "物流信息");
            }
            for (GeneticTestingExpressDeliveryDto deliveryDto : deliveryDtos) {
                if (deliveryDto.getExpressCompany() == null || deliveryDto.getRemarks() == null
                    || deliveryDto.getCourierDateTime() == null|| deliveryDto.getExpressNo() == null) {
                    logger.error("deliveryDto order info is not complete", new IllegalArgumentException());
                    return ApiResult.failFormatTip(OrderErrorCode.ORDER_IS_NOT_COMPLETED, "物流信息");
                }
            }
        }
        try {
            int isStatus = consoleOrderService.isStatus(orderId);
            if (isStatus < 1) {
                return ApiResult.fail(OrderErrorCode.PLATFORM_ORDER_STATUS_NOT_IN_STATUS);
            }
            Integer origin = orderService.queryOrderOrigin(orderId);
            ClientType originType = ClientType.getEnum(origin);
            if (ClientType.APP.equals(originType) || ClientType.APPLETS.equals(originType) || ClientType.PC.equals
                    (originType)) {
                return ApiResult.fail(OrderErrorCode.ORDER_DOCTOR_CANNOT_CHANGED);
            }
            consoleOrderService.updatePlatformOrder(platformOrderDto, userInfo.getUserId());
            return ApiResult.succ();
        } catch (Exception e) {
            logger.error(code.getMessage(), e);
            return ApiResult.fail(code);
        }
    }

    /**
     * @param platformOrder 平台订单信息
     * @param type          类型
     * @return com.hsgene.common.util.exception.ErrorCode
     * @description 校验平台订单信息
     * @author maodi
     * @createDate 2018/11/6 9:06
     */
    private ErrorCode checkPlatformOrder(PlatformOrderDto platformOrder, Integer type) {
        if (1 == type) {
            String patientName = platformOrder.getName();
            if (StringUtils.isBlank(patientName)) {
                return OrderErrorCode.PATIENT_NAME_IS_NOT_NULL;
            }
            String phone = platformOrder.getPhone();
            Integer age = platformOrder.getAge();
            Integer sex = platformOrder.getSex();
            if (StringUtils.isBlank(phone)) {
                return OrderErrorCode.PATIENT_PHONE_IS_NOT_NULL;
            }
            if (StringUtils.isNotBlank(phone)) {
                if (!SimpleRegexUtils.isMobile(phone)) {
                    return CommonErrorCode.MOBILE_IS_ERROR;
                }
            }
            if (age == null) {
                return OrderErrorCode.PATIENT_AGE_IS_NOT_NULL;
            }
            if (age != null) {
                if (!SimpleStringUtils.isPositiveInteger(age.toString())) {
                    return CommonErrorCode.AGE_IS_ERROR;
                }
            }
            if (sex == null) {
                return OrderErrorCode.PATIENT_SEX_IS_NULL;
            }
            if (sex != null) {
                if (sex != 0 && sex != 1) {
                    return CommonErrorCode.SEX_IS_ERROR;
                }
            }
            String clinicalDiagnosis = platformOrder.getClinicalDiagnosis();
            if (StringUtils.isBlank(clinicalDiagnosis)) {
                return OrderErrorCode.CLINICAL_DIAGNOSIS_IS_NOT_NULL;
            }
        } else {
            String doctorId = platformOrder.getDoctorId();
            if (StringUtils.isBlank(doctorId)) {
                return OrderErrorCode.DOCTOR_ID_IS_NULL;
            }
            String doctorName = platformOrder.getDoctorName();
            if (StringUtils.isBlank(doctorName)) {
                return OrderErrorCode.DOCTOR_NAME_IS_NULL;
            }
            String doctorPhone = platformOrder.getDoctorPhone();
            if (StringUtils.isBlank(doctorPhone)) {
                return OrderErrorCode.DOCTOR_PHONE_IS_NULL;
            }
        }
        return null;
    }

    /**
     * @param groundServantId
     * @description 根据地服id获取医生信息
     * @author maodi
     * @createDate 2018/11/5 18:03
     */
    @GetMapping("doctors/{ground_servant_id}")
    public ApiResult<List<DoctorDto>> getDoctorsByGroundServant(@PathVariable("ground_servant_id") String
                                                                        groundServantId) {
        try {
            if (StringUtils.isBlank(groundServantId)) {
                return ApiResult.fail(OrderErrorCode.GROUND_SERVANT_ID_IS_NULL);
            }
            List<DoctorDto> result = consoleOrderService.queryDoctorByHttpNoPage(groundServantId);
            return ApiResult.succ(result);
        } catch (Exception e) {
            logger.error(OrderErrorCode.QUERY_DOCTORS_BY_GROUND_SERVANT_ID_IS_ERROR.getMessage(), e);
            return ApiResult.fail(OrderErrorCode.QUERY_DOCTORS_BY_GROUND_SERVANT_ID_IS_ERROR);
        }
    }

    /**
     * @param name            医生姓名
     * @param phone           医生电话
     * @param groundServantId 地服id
     * @param page            分页
     * @param size            每页数量
     * @description 查询医生信息
     * @author maodi
     * @createDate 2018/11/5 18:04
     */
    @GetMapping("doctors")
    public ApiResult<Pagination<DoctorDto>> queryDoctors(
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "groundServantId") String groundServantId,
            @RequestParam("page") Integer page,
            @RequestParam("size") Integer size) {
        try {
            if (!SimpleStringUtils.isPositiveInteger(page.toString())) {
                return ApiResult.fail(CommonErrorCode.PAGE_IS_NOT_POSITIVE_INTEGER);
            }
            if (!SimpleStringUtils.isPositiveInteger(size.toString())) {
                return ApiResult.fail(CommonErrorCode.SIZE_IS_NOT_POSITIVE_INTEGER);
            }
            if (StringUtils.isBlank(groundServantId)) {
                return ApiResult.fail(OrderErrorCode.GROUND_SERVANT_ID_IS_NULL);
            }
            if (page == null) {
                return ApiResult.fail(CommonErrorCode.PAGE_IS_NULL);
            }
            if (!SimpleStringUtils.isPositiveInteger(page.toString())) {
                return ApiResult.fail(CommonErrorCode.PAGE_IS_NOT_POSITIVE_INTEGER);
            }
            if (size == null) {
                return ApiResult.fail(CommonErrorCode.SIZE_IS_NULL);
            }
            if (!SimpleStringUtils.isPositiveInteger(size.toString())) {
                return ApiResult.fail(CommonErrorCode.SIZE_IS_NOT_POSITIVE_INTEGER);
            }
            LimitHelper limitHelper = LimitHelper.create(page, size);
            PeanutPagination pp = consoleOrderService.queryDoctorByHttp(groundServantId, name, phone, page, size);
            Pagination<DoctorDto> pagination = Pagination.newInstance(limitHelper, pp.getCount());
            List<DoctorDto> result = new ArrayList<>();
            dealPeanutPagination(pp, result);
            int start = (page - 1) * size + 1;
            for (DoctorDto doctorDto : result) {
                doctorDto.setNum(start++);
            }
            pagination.setResult(result);
            return ApiResult.succ(pagination);
        } catch (Exception e) {
            logger.error(OrderErrorCode.QUERY_DOCTORS_IS_ERROR.getMessage(), e);
            return ApiResult.fail(OrderErrorCode.QUERY_DOCTORS_IS_ERROR);
        }
    }

    /***
     *平台端确认样本弹窗信息获取
     * @author jcl
     * @date 2018/11/8 15:36
     * @param orderId 订单id
     * @return
     */
    @GetMapping("order/{order_id}/sample/confirm")
    public ApiResult sampleConfirmInfo(@PathVariable("order_id") String orderId) {
        try {
            return consoleOrderService.sampleConfirmInfo(orderId);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("平台端获取确认样本弹窗信息出现异常");
            return new ApiResult(500, "failed", "取确认样本弹窗信息出现异常", e.toString());
        }
    }

    /***
     * 平台端确认样本信息
     * @author jcl
     * @date 2018/11/8 17:07
     * @param orderId 订单id
     * @return
     */
    @PutMapping("order/{order_id}/sample/confirm")
    public ApiResult sampleConfirm(@PathVariable("order_id") String orderId,
                                   @FromSession UserInfo userInfo,
                                   @RequestBody List<OrderSampleConfirmDto> params) {
        try {
            if (userInfo == null) {
                return new ApiResult(5001, "failed", "获取用户信息失败，请重新登录", null);
            }
            return consoleOrderService.sampleConfirm(orderId, userInfo.getUserId(), params);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("平台端确认样本出现异常");
            return new ApiResult(500, "failed", "确认样本出现异常", e.toString());
        }
    }

    /***
     * 平台订单地管确认
     * @author jcl
     * @date 2018/11/9 9:38
     * @param orderId 订单id
     * @return
     */
    @PutMapping("order/{order_id}/ground_manage/confirm")
    public ApiResult groundManageConfirm(@PathVariable("order_id") String orderId,
                                         @RequestBody Map<String, Object> confirm,
                                         @FromSession UserInfo userInfo) {
        try {
            String userId = "";
            if (userInfo != null) {
                userId = userInfo.getUserId();
            }
            return consoleOrderService.groundManageConfirm(orderId, confirm, userId);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("地管确认出现异常");
            return new ApiResult(500, "failed", "地管确认出现异常", e.toString());
        }
    }

    /**
     * 平台上传报告
     *
     * @param orderId
     * @param orderPackageDetail
     * @param userInfo
     * @return
     * @author FX
     * @date 2018/11/7 14:13
     */
    @PutMapping("order/{orderId}/upload/report")
    public ApiResult uploadReport(@PathVariable("orderId") String orderId, @RequestBody List<OrderPackageDetail>
            orderPackageDetail, @FromSession UserInfo userInfo) {
        orderPackageDetail.forEach(c -> {
            c.setGeneticTestingOrderId(orderId);
            c.setUploader(userInfo.getUserId());
        });
        return consoleOrderService.uploadReport(orderPackageDetail, orderId, userInfo.getUserId());
    }

    /**
     * 后台确认报告
     *
     * @param orderId 订单id
     * @return
     * @author FX
     * @date 2018/11/8 14:32
     */
    @PutMapping("orders/{orderId}/confirmation/report")
    public ApiResult confirmationReport(@PathVariable("orderId") String orderId,@FromSession UserInfo userInfo) {
        GeneticTestingOrder geneticTestingOrder = new GeneticTestingOrder();
        geneticTestingOrder.setId(orderId);
        return consoleOrderService.confirmationReport(geneticTestingOrder,userInfo.getUserId());
    }

    /***
     * 订单的套餐信息
     * @author jcl
     * @date 2018/11/13 10:53
     * @param orderId 订单id
     * @return
     */
    @GetMapping("order/{order_id}/packages")
    public ApiResult orderPackages(@PathVariable("order_id") String orderId) {
        try {
            return consoleOrderService.orderPackages(orderId);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取订单套餐信息出现异常");
            return new ApiResult(500, "failed", "获取订单套餐信息出现异常", e.toString());
        }
    }

    /***
     * 获取机构寄送的物品
     * @author jcl
     * @date 2018/12/21 17:41
     * @param orderId 订单id
     * @param packageId 套餐id
     * @return
     */
    @GetMapping("order/{order_id}/{package_id}")
    public ApiResult orderPackageSendItems(@PathVariable("order_id") String orderId, @PathVariable("package_id")
            String packageId) {
        return consoleOrderService.orderPackageSendItems(orderId, packageId);
    }

    /***
     * 平台端签收材料
     * @author jcl
     * @date 2018/11/13 11:32
     * @param orderPackageSign 签收信息
     * @return
     */
    @PostMapping("order/sign")
    public ApiResult<NullObject> orderPackageSign(
            @RequestBody GeneticTestingOrderPackageSign orderPackageSign, @FromSession UserInfo userInfo) {
        String userId = null;
        if (userInfo != null) {
            userId = userInfo.getUserId();
        }
        return consoleOrderService.orderPackageSign(orderPackageSign, userId);
    }

    /**
     * 寄送材料至地服
     *
     * @param orderId  订单id
     * @param delivery 快递信息
     * @return 操作结果
     */
    @PostMapping("orders/{order_id}/delivery")
    public ApiResult<NullObject> deliveryToGroundServant(
            @PathVariable("order_id") String orderId,
            @RequestBody GeneticTestingExpressDelivery delivery) {
        delivery.setOrderId(orderId);
        return consoleOrderService.deliveryToGroundServant(delivery);
    }

    /**
     * 平台寄送给用户（满足是商城下单，并且是用户选择快递的方式）
     *
     * @param orderId
     * @param delivery
     * @return
     * @author FX
     * @date 2018/11/29 14:10
     */
    @PostMapping("orders/{order_id}/send/user")
    public ApiResult<NullObject> sendToUser(@PathVariable("order_id") String orderId,
                                            @RequestBody GeneticTestingExpressDelivery delivery) {
        delivery.setOrderId(orderId);
        return consoleOrderService.sendToUser(delivery);
    }

    /**
     * 获取收货人地址
     *
     * @param adressId 地址id
     * @return
     * @author FX
     * @date 2018/12/7 13:51
     */
    @GetMapping("orders/user/address/{adressId}")
    public ApiResult<UserMallAddress> getUserMallAdress(@PathVariable("adressId") String adressId) {
        return consoleOrderService.getUserMallAdress(adressId);
    }

    /**
     * 查询订单当前地服的收货地址列表，用于填充下拉框选择
     *
     * @return 地址列表
     */
    @GetMapping("orders/{order_id}/servant/address")
    public ApiResult<List<AddressDetails>> queryOrderServantAddress(
            @PathVariable("order_id") String orderId) {
        return consoleOrderService.queryOrderServantAddress(orderId);
    }

    /***
     * 结算列表
     * @author jcl
     * @date 2018/11/13 17:47
     * @param condition 查询条件
     * @return
     */
    @GetMapping("order/settlement")
    public ApiResult orderSettlementPage(SettlementCondition condition,
                                         @RequestParam(defaultValue = "1") Integer page,
                                         @RequestParam(defaultValue = "15") Integer size) {
        try {
            LimitHelper limitHelper = LimitHelper.create(page, size, true);
            condition.setLimitHelper(limitHelper);
            ApiResult apiResult = consoleOrderService.orderSettlementPage(condition);
            return apiResult;
        } catch (Exception e) {
            logger.error("基因检测结算列表出现异常", e);
            return new ApiResult(500, "failed", "基因检测结算列表出现异常", e.toString());
        }
    }

    /**
     * 修改成本
     *
     * @param orderId
     * @param orderPackage
     * @return
     * @author FX
     * @date 2018/11/14 14:18
     */
    @PutMapping("order/{orderId}/cost")
    public ApiResult updateCost(@PathVariable("orderId") String orderId, @RequestBody OrderPackage orderPackage) {
        orderPackage.setGeneticTestingOrderId(orderId);
        return consoleOrderService.updateCost(orderPackage);
    }

    /**
     * 结算
     *
     * @param orderId
     * @param orderPackage
     * @return
     * @author FX
     * @date 2018/11/14 15:23
     */
    @PutMapping("order/{orderId}/settlement")
    public ApiResult settleAccounts(@PathVariable("orderId") String orderId, @RequestBody OrderPackage orderPackage) {
        orderPackage.setGeneticTestingOrderId(orderId);
        return consoleOrderService.settleAccounts(orderPackage);
    }

    /**
     * 批量结算
     *
     * @param orderPackage 传入id主键
     * @return
     * @author FX
     * @date 2018/11/15 13:45
     */
    @PutMapping("order/batchSettlement")
    public ApiResult batchSettlement(@RequestBody List<OrderPackage> orderPackage) {
        return consoleOrderService.batchSettlement(orderPackage);
    }

    /***
     * 预约订单列表
     * @author jcl
     * @date 2018/12/11 14:09
     * @param size 大小
     * @param page 页码
     * @param orderNo 订单编号
     * @param groundServantName 地服名称
     * @param patientName 患者名称
     * @param doctorPhone 医生电话
     * @param agencyName 机构名称
     * @param sampleBarcode 样本条码
     * @param status 订单状态
     * @param startDate 下单开始时间
     * @param endDate 下单结束时间
     * @param sortField 排序字段
     * @param sortType 排序类型
     * @param chargeStatus 付费状态
     * @return
     */
    @GetMapping("appointment/orders")
    public ApiResult appointmentOrders(
            @RequestParam(value = "size", defaultValue = "15") int size,
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(name = "orderNo", required = false) String orderNo,
            @RequestParam(name = "groundServantName", required = false) String groundServantName,
            @RequestParam(name = "patientName", required = false) String patientName,
            @RequestParam(name = "doctorPhone", required = false) String doctorPhone,
            @RequestParam(name = "agencyName", required = false) String agencyName,
            @RequestParam(name = "sampleBarcode", required = false) String sampleBarcode,
            @RequestParam(name = "status", required = false) String status,
            @RequestParam(name = "startDate", required = false) String startDate,
            @RequestParam(name = "endDate", required = false) String endDate,
            @RequestParam(name = "sortField", required = false, defaultValue = "createDateTime") String sortField,
            @RequestParam(name = "sortType", defaultValue = "desc") String sortType,
            @RequestParam(name = "chargeStatus", required = false) String chargeStatus) {
        LimitHelper limitHelper = LimitHelper.create(page, size, true);
        QueryTestingProductOrderCondition condition = new QueryTestingProductOrderCondition();
        //排序
        ErrorCode code = OrderController.checkSortField(sortField, sortType, condition);
        if (code != null) {
            return ApiResult.fail(code);
        }
        condition.setOrderNo(orderNo);
        condition.setGroundServantName(groundServantName);
        condition.setPatientName(patientName);
        condition.setDoctorPhone(doctorPhone);
        condition.setSampleBarcode(sampleBarcode);
        condition.setStatus(status);
        condition.setStartDate(startDate);
        condition.setEndDate(endDate);
        condition.setAgencyName(agencyName);
        condition.setOrderOrigin(ClientType.GOLD_COLORED_GLASS.getCode().toString());
        condition.setChargeStatus(chargeStatus);
        //判断下单开始时间是否小于下单结束时间，如果不是则提示
        if (condition.getStartDate() != null && condition.getEndDate() != null) {
            if (condition.getStartDate().getTime() > condition.getEndDate().getTime()) {
                return ApiResult.fail(OrderErrorCode.ORDER_START_TIME_CAN_NOT_BEFORE_ORDER_END_TIME);
            }
        }
        ApiResult apiResult = consoleOrderService.queryConsoleOrders(condition, limitHelper, sortType);
        return apiResult;
    }

    /***
     * 变更套餐
     * @author jcl
     * @date 2018/12/21 14:15
     * @param orderReplacePackageDtos
     * @return
     */
    @PutMapping("/orders/{order_id}/replace")
    public ApiResult replaceOrderPackage(@PathVariable("order_id") String orderId,
                                         @FromSession UserInfo userInfo,
                                         @RequestBody List<OrderReplacePackageDto> orderReplacePackageDtos) {
        String userId = null;
        if (userInfo != null) {
            userId = userInfo.getUserId();
        }
        return consoleOrderService.replaceOrderPackage(orderReplacePackageDtos, orderId, userId);
    }

    /**
     * @param pp     金琉璃数据
     * @param result 因子网数据
     * @return void
     * @description 处理请求金琉璃的数据为因子网使用
     * @author maodi
     * @createDate 2019/1/9 15:52
     */
    private void dealPeanutPagination(PeanutPagination pp, List<DoctorDto> result) {
        pp.getList().stream().forEach(li -> {
            DoctorDto dto = new DoctorDto();
            Map<String, Object> map = (Map<String, Object>) li;
            String id = map.get("id").toString();
            dto.setId(id);
            dto.setRealName(map.get("name").toString());
            dto.setPhone(map.get("phone").toString());
            dto.setPost(map.get("postName").toString());
            dto.setIsCertification(Integer.valueOf(map.get("auth").toString()));
            dto.setDept(map.get("deptName").toString());
            dto.setUserId(id);
            result.add(dto);
        });
    }

    /**
     * 备注超期检测订单
     *
     * @param orderId      订单id
     * @param postponeInfo 超期检测订单信息
     * @param userInfo     操作用户信息
     * @return 操作结果
     */
    @PutMapping("orders/postpone/{order_id}")
    public ApiResult<NullObject> remarkPostponeOrder(
            @PathVariable("order_id") String orderId,
            @RequestBody PostponeTestingOrderDto postponeInfo,
            @FromSession UserInfo userInfo) {
        postponeInfo.setOrderId(orderId);
        return consoleOrderService.remarkPostponeOrder(postponeInfo, userInfo.getUserId());
    }

}
